<template>
  <div>
    <div class="allsearch">
      <section class="search-content">
        <el-row style="width:100%;">
          <el-col :span="10">
            <el-input
              v-model="listQuery.title"
              placeholder="标题关键字"
              style="width:97%;"
              @keyup.enter.native="handleFilter"
            />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="medium" @click="handleFilter">搜索</el-button>
            <el-button size="medium" type="info" @click="clearParams">清空</el-button>
          </el-col>
          <el-col :span="5">
            <div style="width:100%">
              <el-button type="primary" size="medium" style="float:right;" @click="goAddPage">新增</el-button>
            </div>
          </el-col>
        </el-row>
      </section>
    </div>
    <el-table
      :table-label="infoLabel"
      :table-data="listFilter.slice((currentpage-1)*pagesize,currentpage*pagesize)"
      :list-loading="listLoading"
      style="margin-top:20px;"
      @handleGoods="handleGoods"
    >
      <el-table-column slot="button" :min-width="10" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-dropdown
            split-button
            type="primary"
            @click="handleClick(scope.row)"
            @command="handleCommand($event,scope.row)"
          >编辑
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="4">永久删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
  </div>
</template>

<script>
  import ElTable from '@/components/Eltable'
  import Pagination from '@/components/Pagination' // 分页组件
  import { scrollTo } from "@/utils/scrollTo" // 上下滑动组件
  import { DeleteStatus, getCategory, getNewInformation, updateStatus } from '@/api/operate/information' // 接口
  import { getTenantId } from '@/utils/auth'

  export default {
    components: {
      ElTable,
      Pagination,
      scrollTo
    },
    data() {
      return {
        value: '',
        listLoading: false,
        total: 0,
        currentpage: 1,
        listFilter: [],
        pagesize: 10,
        listQuery: {
          status: '', // 状态
          categoryId: '', // 栏目
          title: '', // 标题
          property: '' // 属性
        },
        infoLabel: [
          {
            label: 'ID', width: '7', prop: 'id'
          }, {
            label: '标题', width: '30', prop: 'title', isOpera: true
          }, {
            label: '详情', width: '30', prop: 'body', isOpera: true
          }, {
            label: '创建时间', width: '18', prop: 'createTimeTimeStr'
          }
        ],
        infoData: [],
        restaurants: '',
        status: [
          {
            value: '已发布',
            label: '已发布'
          }, {
            value: '未发布',
            label: '未发布'
          }, {
            value: '回收站',
            label: '回收站'
          }, {
            value: '',
            label: '--状态--'
          }
        ],
        property: [
          {
            label: '头条',
            value: 'featured'
          },
          {
            label: '推荐',
            value: 'promoted'
          },
          {
            label: '置顶',
            value: 'sticky'
          },
          {
            label: '--属性--',
            value: ''
          }
        ],
        classify: []
      }
    },
    mounted() {
      this.restaurants = this.loadAll()
      this.getInfoData()
      // 筛选出需要的id 和 label 放到classify
      getCategory(getTenantId()).then(response => {
        const classify = response.data.items.map(item => {
          const data = {}
          data.label = item.name
          data.value = item.id
          return data
        })
        classify.push({ label: '--所属栏目--', value: '' })
        this.classify = classify
      })
    },
    methods: {
      // 检索列表,return所需数据
      handleFilter() {
        this.listFilter = this.infoData.filter(item => {
          if (!this.listQuery.status && !this.listQuery.title && !this.listQuery.property && !this.listQuery.categoryId) return true
          if (this.listQuery.property && item[this.listQuery.property] === false) return false
          if (this.listQuery.status && item.status !== this.listQuery.status) return false
          if (this.listQuery.categoryId && item.categoryId !== this.listQuery.categoryId) return false
          return !(this.listQuery.title && item.title.toLowerCase().indexOf(this.listQuery.title.toLowerCase()) < 0);
        })
        this.total = this.listFilter.length
      },
      clearParams() {
        this.listQuery.status = ''
        this.listQuery.categoryId = ''
        this.listQuery.title = ''
        this.listQuery.property = ''
        this.getInfoData()
      },
      // 属性变更接口
      changeProperty(row) {
        updateStatus(this.changeStatus(row)).then(() => {
          console.log('属性更改成功', this.changeStatus(row))
        })
      },
      handleClick(row) {
        // 带数据跳转到 新增资讯页面
        this.$router.push({ name: 'Add-article', params: row })
      },
      handleGoods(row) {
      },
      // 改变分页页数
      handleSizeChange(val) {
        this.currentpage = 1
        this.pagesize = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      // 改变当前页
      handleCurrentChange(val) {
        this.currentpage = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      // 表格操作按钮
      handleCommand(command, row) {
        if (command === '1') {
          row.status = '已发布'
          updateStatus(this.changeStatus(row)).then(res => {
            this.$notify({
              title: '成功',
              message: '发布成功',
              type: 'success',
              duration: 2000
            })
          })
        } else if (command === '2') {
          row.status = '未发布'
          updateStatus(this.changeStatus(row)).then(res => {
            this.$notify({
              title: '成功',
              message: '取消发布成功',
              type: 'success',
              duration: 2000
            })
          })
        } else if (command === '3') {
          row.status = '回收站'
          updateStatus(this.changeStatus(row)).then(res => {
            this.$notify({
              title: '成功',
              message: '已放入回收站',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          this.$confirm('此操作将永久删除该咨讯，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            DeleteStatus(row.id).then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getInfoData()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消删除'
            })
          })
        }
      },
      // 数据库需要格式
      changeStatus(row) {
        const addData = Object.assign({}, row)
        if (addData.updateTime) addData.updateTime = Date.parse(new Date(addData.updateTime))
        if (addData.status === '已发布') addData.status = 'published'
        if (addData.status === '未发布') addData.status = 'unpublished'
        if (addData.status === '回收站') addData.status = 'trash'
        return addData
      },
      // 获取表格数据
      getInfoData() {
        this.listLoading = true
        getNewInformation(getTenantId()).then(response => {
          this.infoData = response.data.items.filter(item => {
            if (item.tenantId === getTenantId()) return true
          })
          this.infoData.map(item => {
            if (item.status === 'published') item.status = '已发布'
            if (item.status === 'unpublished' || !item.status) item.status = '未发布'
            if (item.status === 'trash') item.status = '回收站'
          })
          this.listFilter = this.infoData
          this.total = this.infoData.length
          this.listLoading = false
        })
      },
      querySearch(queryString, cb) {
        var restaurants = this.restaurants
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      loadAll() {
        return [
          { 'value': '三全鲜食（北新泾店）', 'address': '长宁区新渔路144号' },
          { 'value': 'Hot honey 首尔炸鸡（仙霞路）', 'address': '上海市长宁区淞虹路661号' },
          { 'value': '新旺角茶餐厅', 'address': '上海市普陀区真北路988号创邑金沙谷6号楼113' },
          { 'value': '泷千家(天山西路店)', 'address': '天山西路438号' }
        ]
      },
      goAddPage() {
        this.$router.push('/operate/add-article')
      }
    }
  }
</script>

<style lang="scss" scoped>
  .allsearch {
    margin-top: 0;
    padding: 0;

    .search-content {
      width: 100%;
    }
  }
</style>
